package serv

import (
	"gorm.io/gorm"
	"server/internal/app/model"
	"server/internal/database"
	"time"
)

var Menu = new(menu)

type menu struct {
	model.MenuRule
	Children []menu `json:"children,omitempty" gorm:"-"`
}

// Tree 树状图
func (a menu) Tree(pid int, rules, groupIds any) []menu {
	Db := database.DB
	var menus []menu
	if rules != "*" {
		Db = Db.Where("id in (?)", groupIds)
	}
	Db.Model(&menus).Where("pid=? and status = ?", pid, 1).Order("weigh desc").Find(&menus)

	if len(menus) == 0 {
		return nil
	}
	for k, v := range menus {
		menus[k].Children = a.Tree(v.ID, rules, groupIds)
	}

	return menus
}

func (a menu) List(pid int, rules, groupIds any) []menu {
	Db := database.DB
	var menus []menu
	if rules != "*" {
		Db = Db.Where("id in (?)", groupIds)
	}
	Db.Model(&menus).Where("pid=?", pid).Order("weigh").Find(&menus)
	if len(menus) == 0 {
		return nil
	}

	var list []menu
	for _, v := range menus {

		v.Children = a.List(v.ID, rules, groupIds)
		list = append(list, v)
	}

	return list
}

// Read 单条
func (a menu) Read(id any) (*gorm.DB, menu) {
	Db := database.DB
	detail := menu{}
	Db.Model(&a).Where("id =?", id).First(&detail)

	return Db, detail

}

// Create 新增
func (a menu) Create(data model.MenuRule) *gorm.DB {
	Db := database.DB

	t := time.Now()
	a.CreateTime = int(t.Unix())
	a.UpdateTime = int(t.Unix())

	return Db.Create(&data)
}

// Update 编辑
func (a menu) Update(data model.MenuRule) *gorm.DB {
	Db := database.DB

	t := time.Now()
	a.UpdateTime = int(t.Unix())

	return Db.Select("*").Updates(&data)

}

// Delete 删除
func (a menu) Delete(ids []int) *gorm.DB {
	Db := database.DB

	return Db.Delete(&a, ids)

}

type selects struct {
	Value    int       `json:"value"`
	Label    string    `json:"label"`
	Children []selects `json:"children,omitempty"`
}

// Select 远程下拉
func (a menu) Select(pid int, rules, groupIds any) []selects {
	Db := database.DB
	var menus []menu
	if rules != "*" {
		Db = Db.Where("id in (?)", groupIds)
	}
	Db.Model(&menus).Where("pid=? and status = ?", pid, 1).Order("weigh desc").Find(&menus)

	var list []selects

	if len(menus) == 0 {
		return nil
	}
	for _, v := range menus {
		list = append(list, selects{
			Value:    v.ID,
			Label:    v.Title,
			Children: a.Select(v.ID, rules, groupIds),
		})
	}

	return list
}
